import 'dart:developer';
import 'package:flutter/material.dart';

// 座位状态改变通知
typedef OnSeatStateChanged = Function(
    int rowIndex, int colIndex, SeatState state);

class SeatView extends StatefulWidget {
  const SeatView({
    super.key,
    this.rows = 10,
    this.columns = 20,
    this.minScale = 0.8,
    this.maxScale = 2.5,
    required this.seatsState,
    required this.selectedIcon,
    required this.unSelectedIcon,
    required this.soldIcon,
    required this.disabledIcon,
    this.size = 18,
    this.onChanged,
  });

  final int rows; //行数
  final int columns; //列数
  final double minScale; //最小放大比例
  final double maxScale; //最大放大比例
  final List<List<SeatState>> seatsState;
  final double size;
  final String selectedIcon;
  final String unSelectedIcon;
  final String soldIcon;
  final String disabledIcon;
  final OnSeatStateChanged? onChanged;

  @override
  State<SeatView> createState() => _SeatViewState();
}

class _SeatViewState extends State<SeatView> {
  @override
  void initState() {
    super.initState();

    Future.delayed(Duration(seconds: 1)).then((value) {
      transformationController.value.scale(1.5);
      setState(() {});
    });
  }

  final SeatIndexBarController controller = SeatIndexBarController(1);

  TransformationController transformationController =
      TransformationController();

  @override
  Widget build(BuildContext context) {
    int rows = widget.rows;
    int columns = widget.columns;
    return LayoutBuilder(builder: (context, constraints) {
      // final double itemWidth = constraints.maxWidth / columns;
      // final double itemHeight = constraints.maxHeight / rows;
      // double itemSize = itemWidth < itemHeight ? itemWidth : itemHeight;
      // itemSize = itemSize > kSeatMaxSize ? kSeatMaxSize : itemSize;
      double itemSize = constraints.maxWidth / 12;

      log("屏幕宽=${constraints.maxWidth} 屏幕高=${constraints.maxHeight} 座位大小= $itemSize");

      return Stack(
        fit: StackFit.expand,
        children: [
          InteractiveViewer(
            transformationController: transformationController,
            minScale: 1,
            maxScale: 2.0,
            boundaryMargin: EdgeInsets.zero,
            // onInteractionUpdate: (details) {
            //   controller.value = details.verticalScale;
            //   log('onInteractionUpdate -->> ${details.horizontalScale} ${details.toString()}');
            // },
            child: Column(
              children: List.generate(rows, (rowIndex) {
                return Row(
                  children: List.generate(columns, (colIndex) {
                    return SeatItemWidget(
                      rowIndex: rowIndex,
                      colIndex: colIndex,
                      size: itemSize,
                      state: getState(rowIndex, colIndex),
                      selectedIcon: widget.selectedIcon,
                      unSelectedIcon: widget.unSelectedIcon,
                      soldIcon: widget.soldIcon,
                      disabledIcon: widget.disabledIcon,
                      onChanged: widget.onChanged,
                    );
                  }),
                );
              }),
            ),
          ),
          Align(
            alignment: Alignment.topLeft,
            child: SeatIndexBar(
              controller: controller,
              rows: rows,
              size: itemSize,
            ),
          ),
        ],
      );
    });
  }

  SeatState getState(int rowIndex, int colIndex) {
    if (widget.seatsState.length > rowIndex &&
        widget.seatsState[rowIndex].length > colIndex) {
      return widget.seatsState[rowIndex][colIndex];
    }
    return SeatState.empty;
  }
}

class SeatItemWidget extends StatefulWidget {
  final int rowIndex;
  final int colIndex;
  final SeatState state;
  final String selectedIcon;
  final String unSelectedIcon;
  final String soldIcon;
  final String disabledIcon;
  final double size;
  final OnSeatStateChanged? onChanged;

  const SeatItemWidget({
    super.key,
    required this.rowIndex,
    required this.colIndex,
    required this.state,
    required this.selectedIcon,
    required this.unSelectedIcon,
    required this.soldIcon,
    required this.disabledIcon,
    this.size = 18,
    this.onChanged,
  });

  @override
  State<SeatItemWidget> createState() => _SeatWidgetState();
}

class _SeatWidgetState extends State<SeatItemWidget> {
  late SeatState state;

  @override
  void initState() {
    state = widget.state;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapUp: (_) {
        if (!(state == SeatState.unselected || state == SeatState.selected)) {
          return;
        }
        if (state == SeatState.selected) {
          state = SeatState.unselected;
        } else if (state == SeatState.unselected) {
          state = SeatState.selected;
        }
        setState(() {});
        widget.onChanged?.call(widget.rowIndex, widget.colIndex, state);
      },
      child: state != SeatState.empty
          ? Container(
              width: widget.size,
              height: widget.size,
              padding: const EdgeInsets.all(2),
              child: Image.asset(
                _getIcon(state),
                width: double.maxFinite,
                height: double.maxFinite,
              ),
            )
          : SizedBox(height: widget.size, width: widget.size),
    );
  }

  String _getIcon(SeatState state) {
    switch (state) {
      case SeatState.unselected:
        return widget.unSelectedIcon;
      case SeatState.selected:
        return widget.selectedIcon;
      case SeatState.disabled:
        return widget.disabledIcon;
      case SeatState.sold:
        return widget.soldIcon;
      case SeatState.empty:
      default:
        return widget.disabledIcon;
    }
  }
}

/// 座位状态
enum SeatState {
  /// 已选择的
  selected,

  /// 未选择的
  unselected,

  /// 已售卖的
  sold,

  /// 不能选择的
  disabled,

  /// 空位置
  empty,
}

//座位条
class SeatIndexBar extends StatefulWidget {
  final SeatIndexBarController? controller;
  final double width;
  final int rows;
  final double size;

  const SeatIndexBar({
    super.key,
    this.controller,
    this.rows = 10,
    this.width = 20,
    this.size = 18,
  });

  @override
  State<SeatIndexBar> createState() => _SeatIndexBarState();
}

class _SeatIndexBarState extends State<SeatIndexBar> {
  late SeatIndexBarController controller;

  @override
  void initState() {
    controller = widget.controller ?? SeatIndexBarController(1);
    super.initState();
  }

  final double barWidth = 20;

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<double>(
      valueListenable: controller,
      builder: (BuildContext context, double value, Widget? child) {
        double itemHeight = widget.size * value;
        log("bar总高度=${widget.rows * widget.size * value} 字体大小=${14 * value}");
        return Container(
          width: 20,
          height: widget.rows * itemHeight,
          decoration: BoxDecoration(
            color: Colors.black12,
            borderRadius: BorderRadius.circular(20),
          ),
          child: Column(
            children: List.generate(widget.rows, (index) {
              int rowNumber = index + 1;
              return Container(
                width: widget.width,
                height: itemHeight,
                alignment: Alignment.center,
                child: Text(
                  "$rowNumber",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: getTextSize(rowNumber, value),
                  ),
                ),
              );
            }),
          ),
        );
      },
    );
  }

  getTextSize(int rowNumber, double scale) {
    final double textSize = 14.0 * scale;
    if (rowNumber >= 10) {
      return textSize > 18.0 ? 18.0 : textSize;
    }
    return textSize;
  }
}

class SeatIndexBarController extends ValueNotifier<double> {
  SeatIndexBarController(super.value);
}
